<template>
  <div>
    <div v-for="(item, key, index) in attrList" :key="index">
      {{item.name}}
      <el-radio-group v-model="item.selected" @change="handelchange(item ,key)" size="mini">
        <el-radio v-for="option in item.options" :key="option" :label="option" style="margin: 5px"></el-radio>
      </el-radio-group>
      <div style="margin: 15px 0px 15px 0px;" v-if="item.inputType == 0">
        <el-input placeholder="新增属性" v-model="item.input" class="input-with-select">
          <el-button slot="append" icon="el-icon-plus" @click="handleAddattr(item)"></el-button>
        </el-input>
      </div>
      <el-divider></el-divider>
    </div>
  </div>
</template>

<script>
import { attributeList, updateAttribute } from "@/api/product";
export default {
  props: {
    value: {
      default: null //
    },
    editdata: {
      default: null //选中的sku
    }
  },
  watch: {
    value: {
      handler(newValue, oldValue) {
 
        if (newValue == undefined || newValue.id == null) {
          return;
        }
        
        this.listLoading = true;
        attributeList(newValue.id).then(response => {
          this.listLoading = false;
          this.attrList = response.data;
          this.attrList.forEach(element => {
            if (element.inputList == undefined || element.inputList == "") {
              element.options = [];
            } else {
              element.options = element.inputList.split(",");
            }
          });
        });
      },
      immediate: true
    }
  },
  data() {
    return {
      attrList: {
        options: []
      },
      listLoading: false
    };
  },
  methods: {
    handelchange(item, index) {
      var splist = [];
      for (let i = 0; i < this.attrList.length; i++) {
        var element = this.attrList[i];
        if (element.selected == undefined) {
          return;
        }
        var value = element.id + ":" + element.selected;
        splist.push(value);
      }

      this.$emit("change", splist.join("/"));
    },
    handleAddattr(item) {
      if (item.input.trim().length <= 0) {
        this.$message.error("属性不能为空");
        return;
      }
      if (item.options.indexOf(item.input) < 0) {
        item.options.push(item.input);
        item.inputList = item.options.join(",");
      } else {
        this.$message.error("属性不能重复");
        return;
      }
      this.listLoading = true;
      updateAttribute(item).then(response => {
        this.listLoading = false;
        this.$forceUpdate();
      });
    }
  }
};
</script>